import { useEffect, useMemo } from 'react'
import { useMemoizedFn } from 'ahooks'
import dayjs from 'dayjs'
import { Button, Drawer, Popconfirm, Space } from 'antd'

import { CusAgGrid, ICusAgGridProps } from '@/components/CusAgGrid'
import { disableFutureDate, disableFutureTime } from '@/utils/utils'
import { addAGCellTexty } from '@oBiz/components/addTexty'
import { popupSlot } from '../utils'
import { TCellParams, TCol } from './interface'
import { IBatchAddOrigRouteItem } from './interface'
import { useBoundStore } from './store'
import { createInitialData, isEmptyRow } from './utils'
import countFailImg from '@/assets/countFail.svg'
import countSuccessImg from '@/assets/countSuccess.svg'
import countTotalImg from '@/assets/countTotal.svg'
import styles from './styles.module.less'

const updatePopup = popupSlot.insert(null)

interface IBatchAddOrigRouteDrawerProps {
  onSuccess?: () => void
}

const Cell = (p: TCellParams) => {
  return addAGCellTexty(p)
}

export const BatchAddOrigRouteDrawer = Object.assign(
  ({ onSuccess, destroy }: IBatchAddOrigRouteDrawerProps & { destroy: () => void }) => {
    const { open, onHide, afterOpenChange } = popupSlot.useAntdPopupAnimation(destroy)

    const gridRef = useBoundStore(v => v.gridRef)
    const data = useBoundStore(v => v.data)
    const isValid = useBoundStore(v => v.isValid)
    const submitting = useBoundStore(v => v.submitting)
    const hasSucceeded = useBoundStore(v => v.hasSucceeded)
    const currentCountInfo = useBoundStore(v => v.currentCountInfo)
    const setData = useBoundStore(v => v.setData)
    const validate = useBoundStore(v => v.validate)
    const handleSubmit = useBoundStore(v => v.handleSubmit)

    // 列配置
    const defaultColDef = useMemo<Partial<TCol>>(
      () => ({
        flex: 1,
        minWidth: 180,
        sortable: false,
        mainMenuItems: ['autoSizeThis', 'autoSizeAll', 'separator', 'resetColumns'],
        editable: true,
        cellRenderer: Cell,
        cellClassRules: {
          [styles.is_error]: ({ colDef, value, data }) => {
            if (!colDef.editable) return false
            return !value && !isEmptyRow(data)
          },
          [styles.is_readonly]: ({ colDef }) => !colDef.editable,
          [styles.is_result_error]: ({ data, colDef }) => colDef.field === 'resultDesc' && data?.resultType !== 1,
        },
      }),
      [],
    )
    const columnDefs = useMemo(
      () => [
        {
          field: '序号',
          flex: 0.01,
          minWidth: 62,
          editable: false,
          resizable: false,
          mainMenuItems: [],
          suppressHeaderMenuButton: true,
          valueFormatter: ({ node }) => `${node ? node.childIndex + 1 : ''}`,
        } satisfies TCol<'序号'>,
        {
          field: 'waybillNo',
          headerName: '运单号',
          flex: 1.5,
          minWidth: 130,
        } satisfies TCol<'waybillNo'>,
        {
          field: 'originalRoute',
          headerName: '原始路由',
          flex: 2.5,
          autoHeight: true,
          wrapText: true,
        } satisfies TCol<'originalRoute'>,
        {
          field: 'occurDate',
          headerName: '发生时间',
          flex: 1.5,
          minWidth: 180,
          cellEditor: CusAgGrid.DateCellEditor,
          cellEditorParams: CusAgGrid.DateCellEditor.defineProps({
            datePickerProps: {
              format: 'YYYY-MM-DD HH:mm:ss',
              showTime: { format: 'HH:mm:ss' },
              disabledDate: disableFutureDate,
              disabledTime: disableFutureTime,
            },
          }),
        } satisfies TCol<'occurDate'>,
        {
          field: 'merchantServers',
          headerName: '服务商',
          editable: false,
        } satisfies TCol<'merchantServers'>,
        {
          field: 'channelNo',
          headerName: '渠道单号',
          editable: false,
        } satisfies TCol<'channelNo'>,
        {
          field: 'resultDesc',
          headerName: '导入结果',
          editable: false,
        } satisfies TCol<'resultDesc'>,
      ],
      [],
    )

    // 拖动填充
    const cellSelection = useMemo<ICusAgGridProps['cellSelection']>(
      () => ({
        handle: {
          mode: 'fill',
          direction: 'y',
          suppressClearOnFillReduction: true,
        },
      }),
      [],
    )

    // 值变更
    const onCellValueChanged = useMemoizedFn<
      NonNullable<ICusAgGridProps<IBatchAddOrigRouteItem>['onCellValueChanged']>
    >(({ colDef, newValue, oldValue, node, data }) => {
      if (!colDef.field) return
      oldValue = oldValue?.trim() || '' // oldValue 可能为 null
      newValue = newValue?.trim() || '' // newValue 可能为 null
      if (colDef.field === 'occurDate') {
        if (newValue) {
          const date = dayjs(newValue)
          if (date.isValid()) {
            newValue = date.format($F_YMDHms)
          } else {
            newValue = ''
          }
        }
      }
      node.setData({
        ...data,
        [colDef.field]: newValue,
        ...(newValue !== oldValue
          ? { resultType: undefined, resultDesc: undefined, merchantServers: undefined, channelNo: undefined }
          : {}),
      })
      validate() // 触发校验
    })

    // 触发校验
    useEffect(() => validate(), [data, validate])

    // 初始空行
    useEffect(() => setData(createInitialData()), [setData])

    // 清理
    useEffect(() => () => useBoundStore.setState(useBoundStore.getInitialState(), true), [])

    // 关闭抽屉
    const onClose = () => {
      onHide()
      if (hasSucceeded) onSuccess?.()
    }

    return (
      <Drawer
        title="添加原始路由"
        width={1300}
        open={open}
        onClose={onClose}
        afterOpenChange={afterOpenChange}
        footer={
          <div className={styles.footer}>
            <Space size={20}>
              <span>本次导入结果：</span>
              <Space size={4}>
                <img src={countTotalImg} />
                <span>导入总数</span>
                <b>{currentCountInfo?.totalNum ?? '--'}</b>
              </Space>
              <Space size={4}>
                <img src={countSuccessImg} />
                <span>导入成功</span>
                <b>{currentCountInfo?.successNum ?? '--'}</b>
              </Space>
              <Space size={4}>
                <img src={countFailImg} />
                <span>导入失败</span>
                <b>{currentCountInfo?.failNum ?? '--'}</b>
              </Space>
            </Space>
            <Space>
              <Button onClick={onClose}>取消</Button>
              <Popconfirm
                title="确认要清空吗？"
                onConfirm={() => {
                  gridRef.current?.api?.ensureIndexVisible(0, 'top')
                  setData(createInitialData())
                }}
              >
                <Button disabled={submitting}>清空</Button>
              </Popconfirm>
              <Button type="primary" disabled={!isValid} loading={submitting} onClick={handleSubmit}>
                提交
              </Button>
            </Space>
          </div>
        }
      >
        <div className={styles.main}>
          <div className={styles.main_grid}>
            <CusAgGrid<IBatchAddOrigRouteItem>
              ref={gridRef}
              rowData={data}
              loading={submitting}
              getRowId={undefined}
              defaultColDef={defaultColDef}
              columnDefs={columnDefs}
              suppressMovableColumns
              undoRedoCellEditing
              cellSelection={cellSelection}
              onCellValueChanged={onCellValueChanged}
            />
          </div>
          <div className={styles.main_tip}>注意事项：一次最多导入50条原始路由，超出部分将被自动忽略。</div>
        </div>
      </Drawer>
    )
  },
  {
    open: (props: IBatchAddOrigRouteDrawerProps) => {
      updatePopup(<BatchAddOrigRouteDrawer {...props} destroy={() => updatePopup(null)} />)
    },
  },
)
